import React, { useState, useEffect } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Button,
  Space,
  Alert,
  Divider,
  Typography,
  Row,
  Col,
  AutoComplete,
  Tooltip,
  InputNumber,
  Collapse,
  Tag,
  message
} from 'antd';
import {
  EyeOutlined,
  EyeInvisibleOutlined,
  InfoCircleOutlined,
  ExperimentOutlined,
  BulbOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import ModelStatusIndicator from '../ModelStatusIndicator';
import './style.css';

const { Text, Title } = Typography;
const { Option } = Select;
const { Panel } = Collapse;

interface ModelConfigFormProps {
  visible: boolean;
  config?: any;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  onSuccess?: () => void;  // 可选的成功回调，用于刷新列表
}

interface FormValidationErrors {
  [key: string]: string[];
}

interface ValidationStatus {
  baseUrl: 'success' | 'warning' | 'error' | 'validating' | '';
  apiKey: 'success' | 'warning' | 'error' | 'validating' | '';
  modelName: 'success' | 'warning' | 'error' | 'validating' | '';
}

interface ModelTemplate {
  providerId: string;
  providerName: string;
  defaultBaseUrl: string;
  suggestedModels: Array<{
    name: string;
    displayName: string;
    description: string;
    maxTokens?: number;
  }>;
}

// 模型模板数据
const MODEL_TEMPLATES: ModelTemplate[] = [
  {
    providerId: 'openai',
    providerName: 'OpenAI',
    defaultBaseUrl: 'https://api.openai.com/v1',
    suggestedModels: [
      { name: 'gpt-4', displayName: 'GPT-4', description: '最强大的GPT模型', maxTokens: 8192 },
      { name: 'gpt-4-turbo', displayName: 'GPT-4 Turbo', description: '更快的GPT-4版本', maxTokens: 128000 },
      { name: 'gpt-4o', displayName: 'GPT-4o', description: '多模态GPT-4', maxTokens: 128000 },
      { name: 'gpt-3.5-turbo', displayName: 'GPT-3.5 Turbo', description: '高效的对话模型', maxTokens: 4096 }
    ]
  },
  {
    providerId: 'claude',
    providerName: 'Anthropic Claude',
    defaultBaseUrl: 'https://api.anthropic.com',
    suggestedModels: [
      { name: 'claude-sonnet-4-20250514', displayName: 'Claude Sonnet 4', description: '最新最强的Claude模型', maxTokens: 100000 },
      { name: 'claude-3-5-sonnet-20241022', displayName: 'Claude 3.5 Sonnet', description: '平衡性能与速度的模型', maxTokens: 100000 },
      { name: 'claude-3-5-haiku-20241022', displayName: 'Claude 3.5 Haiku', description: '快速响应的轻量模型', maxTokens: 100000 },
      { name: 'claude-3-opus-20240229', displayName: 'Claude 3 Opus', description: '强大的推理能力模型', maxTokens: 100000 }
    ]
  },
  {
    providerId: 'deepseek',
    providerName: 'DeepSeek',
    defaultBaseUrl: 'https://api.deepseek.com',
    suggestedModels: [
      { name: 'deepseek-chat', displayName: 'DeepSeek Chat', description: '通用对话模型', maxTokens: 32000 },
      { name: 'deepseek-coder', displayName: 'DeepSeek Coder', description: '代码生成专用', maxTokens: 32000 }
    ]
  },
  {
    providerId: 'qwen',
    providerName: '阿里通义千问',
    defaultBaseUrl: 'https://dashscope.aliyuncs.com',
    suggestedModels: [
      { name: 'qwen-max', displayName: '通义千问-Max', description: '最强版本', maxTokens: 6000 },
      { name: 'qwen-plus', displayName: '通义千问-Plus', description: '平衡版本', maxTokens: 6000 },
      { name: 'qwen-turbo', displayName: '通义千问-Turbo', description: '快速版本', maxTokens: 6000 }
    ]
  },
  {
    providerId: 'kimi',
    providerName: '月之暗面 Kimi',
    defaultBaseUrl: 'https://api.moonshot.cn/v1',
    suggestedModels: [
      { name: 'moonshot-v1-8k', displayName: 'Kimi 8K', description: '8K上下文版本', maxTokens: 8000 },
      { name: 'moonshot-v1-32k', displayName: 'Kimi 32K', description: '32K上下文版本', maxTokens: 32000 },
      { name: 'moonshot-v1-128k', displayName: 'Kimi 128K', description: '128K上下文版本', maxTokens: 128000 }
    ]
  },
  {
    providerId: 'doubao',
    providerName: '字节豆包',
    defaultBaseUrl: 'https://ark.cn-beijing.volces.com/api/v3',
    suggestedModels: [
      { name: 'ep-20241203', displayName: '豆包主力模型', description: '通用对话模型', maxTokens: 32000 },
      { name: 'ep-20241203-character', displayName: '豆包角色模型', description: '角色扮演专用', maxTokens: 32000 },
      { name: 'ep-20241203-instruct', displayName: '豆包指令模型', description: '指令遵循优化', maxTokens: 32000 }
    ]
  }
];

const ModelConfigForm: React.FC<ModelConfigFormProps> = ({
  visible,
  config,
  onCancel,
  onSubmit,
  onSuccess
}) => {
  const [form] = Form.useForm();
  const [showApiKey, setShowApiKey] = useState(false);
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<{
    status: 'success' | 'error' | 'warning';
    message: string;
    details?: any;
  } | null>(null);
  const [selectedProvider, setSelectedProvider] = useState<string>('');
  const [suggestedModels, setSuggestedModels] = useState<Array<{name: string; displayName: string; description: string}>>([]);
  const [loadingModels, setLoadingModels] = useState(false);
  const [discoveredModels, setDiscoveredModels] = useState<Array<{name: string; displayName: string; description: string}>>([]);
  const [validationStatus, setValidationStatus] = useState<ValidationStatus>({
    baseUrl: '',
    apiKey: '',
    modelName: ''
  });
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [formErrors, setFormErrors] = useState<FormValidationErrors>({});

  useEffect(() => {
    if (visible) {
      if (config) {
        // 编辑模式
        form.setFieldsValue({
          providerId: config.providerId,
          providerName: config.providerName,
          baseUrl: config.baseUrl,
          apiKey: config.apiKey,  // 注意：这是被mask的值
          modelName: config.modelName,
          displayName: config.displayName,
          isActive: config.isActive,
          maxTokens: config.maxTokens,
          temperature: config.temperature,
          topP: config.topP,
          description: config.description,
          tags: config.tags
        });
        setSelectedProvider(config.providerId);
        updateSuggestedModels(config.providerId);
      } else {
        // 新增模式
        form.resetFields();
        setSelectedProvider('');
        setSuggestedModels([]);
      }
      setTestResult(null);
    }
  }, [visible, config, form]);

  const updateSuggestedModels = (providerId: string) => {
    const template = MODEL_TEMPLATES.find(t => t.providerId === providerId);
    setSuggestedModels(template?.suggestedModels || []);
    // 清空之前发现的模型
    setDiscoveredModels([]);
  };

  const handleDiscoverModels = async () => {
    console.log('[DISCOVER] Starting model discovery...');
    console.log('[DISCOVER] selectedProvider:', selectedProvider);
    console.log('[DISCOVER] form providerId:', form.getFieldValue('providerId'));
    
    try {
      setLoadingModels(true);
      
      const baseUrl = form.getFieldValue('baseUrl');
      const apiKey = form.getFieldValue('apiKey');
      const provider = form.getFieldValue('providerId');
      
      console.log('[DISCOVER] Form values:', { baseUrl, provider, apiKeyLength: apiKey?.length });
      
      if (!baseUrl || !apiKey || !provider) {
        message.warning('请先填写Base URL、API Key和选择提供商');
        setLoadingModels(false);
        return;
      }
      
      const modelConfigService = (await import('../../../services/model-config.service')).default;
      console.log('[DISCOVER] Calling discoverModels API...');
      const result = await modelConfigService.discoverModels(baseUrl, apiKey, provider);
      
      console.log('[DISCOVER] API result:', result);
      
      if (result.success && result.models) {
        const models = result.models.map((model: any) => ({
          name: model.id,
          displayName: model.name || model.id,
          description: `${provider} 模型`
        }));
        
        console.log('[DISCOVER] Processed models:', models);
        setDiscoveredModels(models);
        message.success(`发现 ${models.length} 个可用模型`);
      } else {
        console.error('[DISCOVER] API failed:', result.error);
        message.error(result.error || '获取模型列表失败');
      }
    } catch (error) {
      console.error('Failed to discover models:', error);
      message.error('获取模型列表失败: ' + (error instanceof Error ? error.message : '未知错误'));
    } finally {
      setLoadingModels(false);
    }
  };

  const handleProviderChange = (providerId: string) => {
    setSelectedProvider(providerId);
    const template = MODEL_TEMPLATES.find(t => t.providerId === providerId);
    
    if (template) {
      form.setFieldsValue({
        providerName: template.providerName,
        baseUrl: template.defaultBaseUrl
      });
      updateSuggestedModels(providerId);
    }
  };

  const handleModelNameSelect = (modelName: string) => {
    const model = suggestedModels.find(m => m.name === modelName);
    if (model) {
      form.setFieldsValue({
        displayName: model.displayName
      });
    }
  };

  const validateField = async (field: string, value: string) => {
    setValidationStatus(prev => ({ ...prev, [field]: 'validating' }));
    
    try {
      switch (field) {
        case 'baseUrl':
          if (!value) {
            setValidationStatus(prev => ({ ...prev, baseUrl: '' }));
            return;
          }
          
          // URL format validation
          const urlPattern = /^https?:\/\/.+/;
          if (!urlPattern.test(value)) {
            setValidationStatus(prev => ({ ...prev, baseUrl: 'error' }));
            return;
          }
          
          // Check if URL is reachable (simulate)
          await new Promise(resolve => setTimeout(resolve, 500));
          setValidationStatus(prev => ({ ...prev, baseUrl: 'success' }));
          break;
          
        case 'apiKey':
          if (!value) {
            setValidationStatus(prev => ({ ...prev, apiKey: '' }));
            return;
          }
          
          // Basic API key format validation
          if (value.length < 10) {
            setValidationStatus(prev => ({ ...prev, apiKey: 'error' }));
            return;
          }
          
          setValidationStatus(prev => ({ ...prev, apiKey: 'success' }));
          break;
          
        case 'modelName':
          if (!value) {
            setValidationStatus(prev => ({ ...prev, modelName: '' }));
            return;
          }
          
          // Check if model exists in suggestions
          const modelExists = suggestedModels.some(m => m.name === value);
          setValidationStatus(prev => ({ 
            ...prev, 
            modelName: modelExists ? 'success' : 'warning' 
          }));
          break;
      }
    } catch (error) {
      setValidationStatus(prev => ({ ...prev, [field]: 'error' }));
    }
  };

  const handleTestConnection = async () => {
    console.log('[TEST] Test connection button clicked');
    console.log('[TEST] Current form values:', {
      baseUrl: form.getFieldValue('baseUrl'),
      apiKey: form.getFieldValue('apiKey')?.substring(0, 10) + '...',
      modelName: form.getFieldValue('modelName'),
      providerId: form.getFieldValue('providerId')
    });
    
    setTesting(true);
    setTestResult(null);
    
    try {
      // 验证baseUrl字段
      let values;
      try {
        values = await form.validateFields(['baseUrl']);
      } catch (validationError) {
        console.error('[TEST] Form validation failed:', validationError);
        message.error('请填写有效的 Base URL');
        setTesting(false);
        return;
      }

      // 调用真实的API测试服务
      const modelConfigService = (await import('../../../services/model-config.service')).default;
      
      // 获取当前表单中的API key值
      const currentApiKey = form.getFieldValue('apiKey');
      
      // 构建测试配置
      const testConfig: any = {
        baseUrl: values.baseUrl,
        modelName: form.getFieldValue('modelName') || 'deepseek-chat', // 使用已知存在的模型
        providerId: form.getFieldValue('providerId') || 'unknown'
      };
      
      // 判断是否使用新输入的API key
      const isEdit = !!config;  // 是否为编辑模式
      const initialValues = config;  // 初始值就是传入的config
      
      if (isEdit && initialValues?.id) {
        // 编辑模式下
        console.log('[TEST] Edit mode - currentApiKey:', currentApiKey?.substring(0, 10) + '...');
        console.log('[TEST] Edit mode - initialApiKey:', initialValues.apiKey?.substring(0, 10) + '...');
        
        // 检查当前API key是否看起来是被截断的
        const isCurrentKeyTruncated = currentApiKey && (
          currentApiKey.includes('***') || 
          currentApiKey.includes('...') || 
          currentApiKey.length < 20
        );
        
        if (isCurrentKeyTruncated && currentApiKey === initialValues.apiKey) {
          // API key是被截断的，需要用户重新输入
          message.warning('当前API Key可能已失效，请重新输入完整的API Key');
          setTesting(false);
          return;
        }
        
        if (currentApiKey && currentApiKey !== initialValues.apiKey && !currentApiKey.includes('***')) {
          // 用户输入了新的API key，使用新key测试
          testConfig.apiKey = currentApiKey;
          console.log('[TEST] Using new API key for test');
        } else {
          // 使用configId让后端使用存储的完整key
          testConfig.configId = initialValues.id;
          console.log('[TEST] Using stored API key via configId:', initialValues.id);
        }
      } else {
        // 新建模式，必须有API key
        if (!currentApiKey) {
          message.error('请输入API Key');
          setTesting(false);
          return;
        }
        testConfig.apiKey = currentApiKey;
      }
      
      console.log('[TEST] Calling real API test with config:', { ...testConfig, apiKey: testConfig.apiKey ? '***masked***' : 'using-stored' });
      
      const result = await modelConfigService.testModelConnection(testConfig);
      
      console.log('[TEST] API test result:', result);
      console.log('[TEST] result.success:', result.success);
      console.log('[TEST] result.status:', result.status);
      console.log('[TEST] typeof result.success:', typeof result.success);
      
      // 确保正确处理响应
      if (result && (result.success === true || result.status === 'healthy')) {
        setTestResult({
          status: 'success',
          message: result.message || `连接测试成功！响应时间: ${result.responseTime}ms`,
          details: {
            responseTime: result.responseTime,
            modelInfo: result.modelInfo
          }
        });
        message.success('模型连接测试成功');
        
        // 如果是编辑模式且测试成功，立即更新健康状态到数据库
        if (isEdit && initialValues.id) {
          console.log('[TEST] 测试成功，自动更新健康状态');
          try {
            // 构建更新数据，只更新状态相关字段
            const updateData = {
              ...initialValues,
              status: 'healthy',
              lastChecked: new Date()
            };
            
            // 调用更新服务
            await modelConfigService.updateModelConfig(initialValues.id, updateData);
            console.log('[TEST] 健康状态已更新到数据库');
            
            // 立即触发父组件刷新列表
            if (onSuccess) {
              console.log('[TEST] 调用onSuccess回调刷新列表');
              onSuccess();
            }
          } catch (updateError) {
            console.error('[TEST] 更新健康状态失败:', updateError);
            // 不显示错误消息，避免影响用户体验
          }
        }
      } else {
        setTestResult({
          status: 'error',
          message: result.message || '连接测试失败',
          details: { error: result.error || result.message }
        });
        message.error(result.message || '模型连接测试失败');
      }
    } catch (error) {
      console.error('[TEST] Connection test error:', error);
      const errorMessage = error instanceof Error ? error.message : '连接测试失败';
      setTestResult({
        status: 'error',
        message: errorMessage
      });
      message.error(errorMessage);
    } finally {
      setTesting(false);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // Enhanced validation
      const errors: FormValidationErrors = {};
      
      // Check for duplicate configurations
      if (!config) { // Only check for duplicates when creating new config
        const isDuplicate = false; // This would check against existing configs
        if (isDuplicate) {
          errors.general = ['该模型配置已存在'];
        }
      }
      
      if (Object.keys(errors).length > 0) {
        setFormErrors(errors);
        message.error('请检查表单中的错误');
        return;
      }
      
      // Process tags
      if (values.tags && typeof values.tags === 'string') {
        values.tags = values.tags.split(',').map((tag: string) => tag.trim()).filter(Boolean);
      }
      
      // 如果测试成功，添加健康状态到提交数据
      if (testResult && testResult.status === 'success') {
        values.status = 'healthy';
        values.lastChecked = new Date();
        console.log('[SUBMIT] 测试成功，设置状态为 healthy');
      } else {
        // 如果没有测试或测试失败，状态为unknown
        values.status = 'unknown';
        console.log('[SUBMIT] 未测试或测试失败，设置状态为 unknown');
      }
      
      // 调用父组件的提交函数并等待结果
      await onSubmit(values);
      // 成功消息将由父组件显示
    } catch (error) {
      console.error('Form validation failed:', error);
      message.error('表单验证失败，请检查必填项');
    }
  };

  const getModelNameOptions = () => {
    const allModels = [...suggestedModels, ...discoveredModels];
    const uniqueModels = allModels.filter((model, index, self) => 
      index === self.findIndex(m => m.name === model.name)
    );
    
    return uniqueModels.map(model => ({
      value: model.name,
      label: (
        <div className="model-option">
          <div className="model-option-name">{model.displayName}</div>
          <div className="model-option-description">{model.description}</div>
        </div>
      )
    }));
  };

  return (
    <Modal
      title={
        <div className="form-title">
          <BulbOutlined />
          {config ? '编辑模型配置' : '添加新模型'}
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Button 
            icon={<ExperimentOutlined />}
            onClick={handleTestConnection}
            loading={testing}
          >
            测试连接
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            {config ? '更新配置' : '添加模型'}
          </Button>
        </Space>
      }
      width={720}
      className="model-config-form"
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          isActive: true
        }}
      >
        <Alert
          message="配置说明"
          description="支持配置同一提供商的多个模型。例如Claude可以配置claude-sonnet-4-20250514、claude-3-5-sonnet-20241022等不同版本。"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />

        {selectedProvider === 'claude' && (
          <Alert
            message="Claude模型配置提示"
            description={
              <div>
                <p>Claude模型需要使用Anthropic SDK，不是标准的OpenAI格式。请注意：</p>
                <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                  <li>如果使用官方API，Base URL应为: https://api.anthropic.com</li>
                  <li>如果使用中继服务，请确保服务支持Anthropic格式</li>
                  <li>本系统已经适配了Anthropic SDK，可以正常使用Claude模型</li>
                </ul>
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="提供商"
              name="providerId"
              rules={[{ required: true, message: '请选择提供商' }]}
            >
              <Select
                placeholder="选择AI模型提供商"
                onChange={handleProviderChange}
                showSearch
                filterOption={(input, option) =>
                  option?.children?.toString().toLowerCase().includes(input.toLowerCase()) ?? false
                }
              >
                {MODEL_TEMPLATES.map(template => (
                  <Option key={template.providerId} value={template.providerId}>
                    {template.providerName}
                  </Option>
                ))}
                <Option value="custom">自定义提供商</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="提供商名称"
              name="providerName"
              rules={[{ required: true, message: '请输入提供商名称' }]}
            >
              <Input placeholder="如：OpenAI、Anthropic Claude" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label={
            <span>
              Base URL 
              <Tooltip title="API端点地址，如：https://api.openai.com/v1">
                <InfoCircleOutlined style={{ marginLeft: 4, color: '#8c8c8c' }} />
              </Tooltip>
            </span>
          }
          name="baseUrl"
          validateStatus={validationStatus.baseUrl}
          hasFeedback
          rules={[
            { required: true, message: '请输入Base URL' },
            { type: 'url', message: '请输入有效的URL地址' },
            {
              pattern: /^https?:\/\/.+/,
              message: 'URL必须以http://或https://开头'
            }
          ]}
        >
          <Input 
            placeholder="https://api.example.com/v1" 
            onChange={(e) => validateField('baseUrl', e.target.value)}
          />
        </Form.Item>

        <Form.Item
          label={
            <span>
              API Key
              <Tooltip title="从提供商获取的API密钥">
                <InfoCircleOutlined style={{ marginLeft: 4, color: '#8c8c8c' }} />
              </Tooltip>
            </span>
          }
          name="apiKey"
          validateStatus={validationStatus.apiKey}
          hasFeedback
          rules={[
            { required: true, message: '请输入API Key' },
            { min: 10, message: 'API Key长度至少10个字符' },
            {
              validator: async (_, value) => {
                if (value && value.includes(' ')) {
                  throw new Error('API Key不能包含空格');
                }
              }
            }
          ]}
        >
          <Input.Password
            placeholder="sk-..."
            iconRender={(visible) => (visible ? <EyeOutlined /> : <EyeInvisibleOutlined />)}
            visibilityToggle={{ visible: showApiKey, onVisibleChange: setShowApiKey }}
            onChange={(e) => validateField('apiKey', e.target.value)}
          />
        </Form.Item>

        <Divider>模型信息</Divider>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={
                <span>
                  模型名称
                  <Tooltip title="具体的模型名称，如：gpt-4、claude-4.1等">
                    <InfoCircleOutlined style={{ marginLeft: 4, color: '#8c8c8c' }} />
                  </Tooltip>
                </span>
              }
              name="modelName"
              validateStatus={validationStatus.modelName}
              hasFeedback
              rules={[
                { required: true, message: '请输入或选择模型名称' },
                {
                  pattern: /^[a-zA-Z0-9\-_\.]+$/,
                  message: '模型名称只能包含字母、数字、连字符和下划线'
                }
              ]}
            >
            <div style={{ display: 'flex', gap: 8 }}>
              <AutoComplete
                style={{ flex: 1 }}
                placeholder="输入模型名称或从建议中选择"
                options={getModelNameOptions()}
                onSelect={handleModelNameSelect}
                onChange={(value) => {
                  validateField('modelName', value);
                  handleModelNameSelect(value);
                }}
                filterOption={(inputValue, option) =>
                  option?.value?.toString().toLowerCase().includes(inputValue.toLowerCase()) ?? false
                }
              />
              {selectedProvider === 'deepseek' && (
                <Button 
                  size="middle" 
                  loading={loadingModels}
                  onClick={handleDiscoverModels}
                  title="从API获取可用模型"
                >
                  发现模型
                </Button>
              )}
            </div>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="显示名称"
              name="displayName"
              tooltip="在界面中显示的友好名称"
            >
              <Input placeholder="如：GPT-4 Turbo" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="启用状态"
          name="isActive"
          valuePropName="checked"
        >
          <Switch checkedChildren="启用" unCheckedChildren="禁用" />
        </Form.Item>

        <Collapse 
          ghost 
          onChange={(keys) => setShowAdvanced(keys.includes('advanced'))}
        >
          <Panel 
            header={
              <span>
                <SettingOutlined /> 高级配置 (可选)
              </span>
            } 
            key="advanced"
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="最大Token数"
                  name="maxTokens"
                  tooltip="模型支持的最大token数量"
                >
                  <InputNumber
                    placeholder="4096"
                    min={1}
                    max={200000}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="Temperature"
                  name="temperature"
                  tooltip="控制输出的随机性，范围0-2"
                >
                  <InputNumber
                    placeholder="0.7"
                    min={0}
                    max={2}
                    step={0.1}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="Top P"
                  name="topP"
                  tooltip="核采样参数，范围0-1"
                >
                  <InputNumber
                    placeholder="1.0"
                    min={0}
                    max={1}
                    step={0.1}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="标签"
                  name="tags"
                  tooltip="用逗号分隔多个标签"
                >
                  <Input placeholder="生产,高质量,推荐" />
                </Form.Item>
              </Col>
            </Row>
            
            <Form.Item
              label="描述"
              name="description"
              tooltip="可选的配置描述"
            >
              <Input.TextArea 
                placeholder="描述这个模型配置的用途和特点..."
                rows={3}
                maxLength={500}
                showCount
              />
            </Form.Item>
          </Panel>
        </Collapse>

        {Object.keys(formErrors).length > 0 && (
          <Alert
            message="表单验证错误"
            description={
              <ul style={{ margin: 0, paddingLeft: 20 }}>
                {Object.entries(formErrors).map(([field, errors]) => 
                  errors.map((error, index) => (
                    <li key={`${field}-${index}`}>{error}</li>
                  ))
                )}
              </ul>
            }
            type="error"
            showIcon
            closable
            onClose={() => setFormErrors({})}
            style={{ marginTop: 16 }}
          />
        )}

        {testResult && (
          <Alert
            message={
              <span>
                {testResult.status === 'success' && <CheckCircleOutlined />}
                {testResult.status === 'error' && <ExclamationCircleOutlined />}
                {' '}连接测试结果
              </span>
            }
            description={
              <div>
                <div>{testResult.message}</div>
                {testResult.details && testResult.status === 'success' && (
                  <div style={{ marginTop: 8 }}>
                    <Text type="secondary">
                      模型信息：{testResult.details.modelInfo?.name} v{testResult.details.modelInfo?.version}
                    </Text>
                  </div>
                )}
                {testResult.details && testResult.status === 'error' && (
                  <div style={{ marginTop: 8 }}>
                    <Text type="secondary">
                      错误代码：{testResult.details.errorCode}
                    </Text>
                  </div>
                )}
              </div>
            }
            type={testResult.status}
            showIcon
            closable
            onClose={() => setTestResult(null)}
            style={{ marginTop: 16 }}
          />
        )}

        {(suggestedModels.length > 0 || discoveredModels.length > 0) && (
          <div className="suggested-models">
            <Title level={5}>
              <BulbOutlined /> {discoveredModels.length > 0 ? '可用模型' : '推荐模型'}
              <Text type="secondary" style={{ fontSize: 12, fontWeight: 'normal', marginLeft: 8 }}>
                点击快速选择
              </Text>
              {discoveredModels.length > 0 && (
                <Text type="success" style={{ fontSize: 12, fontWeight: 'normal', marginLeft: 8 }}>
                  (从API动态获取)
                </Text>
              )}
            </Title>
            <div className="model-suggestions">
              {(discoveredModels.length > 0 ? discoveredModels : suggestedModels).map(model => {
                const isSelected = form.getFieldValue('modelName') === model.name;
                return (
                  <div 
                    key={model.name} 
                    className={`model-suggestion ${isSelected ? 'selected' : ''}`}
                    onClick={() => {
                      form.setFieldsValue({
                        modelName: model.name,
                        displayName: model.displayName
                      });
                      validateField('modelName', model.name);
                    }}
                  >
                    <div className="model-header">
                      <Text strong>{model.displayName}</Text>
                      {isSelected && <Tag color="green" size="small">已选择</Tag>}
                      {discoveredModels.includes(model) && <Tag color="blue" size="small">API</Tag>}
                    </div>
                    <Text type="secondary" className="model-code">{model.name}</Text>
                    <Text type="secondary" className="model-desc">{model.description}</Text>
                    {(model as any).maxTokens && (
                      <Text type="secondary" className="model-tokens">
                        最大Token: {(model as any).maxTokens.toLocaleString()}
                      </Text>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </Form>
    </Modal>
  );
};

export default ModelConfigForm;